<template>
  <van-field
    :label="titleText(options, item)"
    :name="item.itemTitle"
    :required="item.isRequired === 'Y'"
    :rules="[
      {
        validator: item.isRequired === 'Y' ? validator : '',
        message: '请选择' + item.itemTitle,
      },
    ]"
    label-width="33rem"
  >
    <template #input>
      <p v-if="options.showDesc" class="desc f12 mb10">
        {{ options.description }}
      </p>
      <div>
        <div v-for="(next, idx) in options.optionItems" :key="next.label">
          <p v-if="options.optionItems.length > 1">{{ next.label }}</p>
          <Rate
            v-model="item.value[idx]"
            :allow-half="optionItemSet.half"
            :count="optionItemSet.maxLength || 5"
            :disabled="type === 'view'"
            :icon="optionItemSet.hasType || 'star'"
            :void-icon="
              optionItemSet.hasType ? optionItemSet.hasType + '-o' : 'star-o'
            "
            color="#1989fa"
            @change="onChange"
          />
          <span
            v-if="optionItemSet.showScore && item.value[idx]"
            class="ml10"
          >{{ item.value[idx] + "分" }}</span
          >
        </div>
      </div>
    </template>
  </van-field>
</template>

<script setup>
import { titleText } from "@/utils/common.js";
import { Rate, showFailToast } from "vant";
import { onBeforeMount, reactive, } from "vue";

//defineOptions({ name: "H5Rate" });

const { item, type } = defineProps(["item", "type"]);
const emits = defineEmits(["change"]);

const options = reactive(JSON.parse(item.vformJson || "{}").options);
const optionItemSet = options.optionItemSet || {};
onBeforeMount(() => {
  if (!item.value) {
    item.value = [];
  }
});
// 传递值改变后
const onChange = () => {
  let bool = false;
  item.value.forEach((val, idx) => {
    if (val < options.optionItemSet.min || val > options.optionItemSet.max) {
      item.value[idx] = null;
      bool = true;
    }
  });
  if (bool)
    showFailToast(
      `值应在${options.optionItemSet.min}~${options.optionItemSet.max}之间`,
    );
  else emits("change", item);
};
// 校验
const validator = (val) => {
  let items = item.value.filter((row) => !!row);
  return items.length === options.optionItems.length;
};
</script>